package com.hsmw.api.config;

import com.hsmw.api.config.jwt.CurrentHsmwUserUtils;
import com.hsmw.api.utils.IpUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Aspect
@Component
public class NoRepeatSubmitAop {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CurrentHsmwUserUtils currentHsmwUserUtils;

    @Pointcut("@annotation(com.hsmw.api.config.NoRepeatSubmit)")
    public void noRepeatSubmitPointCut() {
    }

    @Around("noRepeatSubmitPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();

        NoRepeatSubmit noRepeatSubmit = method.getAnnotation(NoRepeatSubmit.class);

        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();

        // 拿到ip地址、请求路径、token
        String ip = IpUtils.getIpAddr(request);
        String uri = request.getRequestURI();

        // 自定义key值方式
        String userInfo = "";
        Object userId = null;
        try {
            userId = currentHsmwUserUtils.getCurrentUserInfo().getId();
        } catch (Exception e) {
        }

        if (userId != null) {
            userInfo = "web-";
        } else {
            userInfo = "dri-";
        }
        String key = String.format("noRepeatSubmit:%s:%s:%s", userInfo + userId, ip, uri);
        if (redisTemplate.hasKey(key)) {
            throw new Exception("请勿重复提交");
        } else {
            // 这里是第一次操作，设置过期时间
                redisTemplate.opsForValue().set(key, String.valueOf(System.currentTimeMillis() + noRepeatSubmit.time() * 1000), noRepeatSubmit.time(), TimeUnit.MILLISECONDS);
            return pjp.proceed();
        }
    }
}